<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2025-03-18 11:53:48
 * @LastEditors: chenhuanhuan 2925102113@qq.com
 * @LastEditTime: 2025-03-24 11:37:45
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\businessAnalysis\incomeStatistics\components\incomeStatic.vue
-->
<template>
  <div class="incomestatic">
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :inline="true" @keyup.enter="searchFn">
        <el-form-item label="登记日期：">
          <pb-date-picker v-model="planDateRang" placeholder="请输入" @change="dateChange"></pb-date-picker>
        </el-form-item>
        <el-form-item label="收入来源：">
          <pb-select v-model="incomeForm.incomeSource" placeholder="请选择" keys="value" label="lable"
            :options="conmeSourelist" />
        </el-form-item>
        <el-form-item label="单位名称：">
          <pb-select v-model="incomeForm.tenantId" placeholder="请选择" keys="tenantId" label="tenantName"
            :options="kitchenList" />
        </el-form-item>
      </el-form>
    </searchCard>
    <div class="divide-css"></div>
    <!-- 表格区 -->
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <ContentOperation>
          <div mr-6 v-hasPerm="'center:Analysis:mx-import'">
            <pb-import size="small" :action="incomeImportExcel" text="导入" :data="{
              statisticsDate: importDate
            }" :isCheck="true" @onImportSuccerr="searchFn" :showDefualt="true" @downExcelFn="downtemplateExcelFn"
              :showFileList="false">
              <el-form :inline="true">
                <el-form-item label="登记日期：">
                  <pb-date-picker v-model="importDate" placeholder="请输入" type="days"
                    @change="importDateChange"></pb-date-picker>
                </el-form-item>
              </el-form>
            </pb-import>
          </div>
          <pb-button size="small" plain @click="downStatisticFN" v-hasPerm="'center:Analysis:mx-export'">导出</pb-button>
        </ContentOperation>
        <div class="main-box">
          <pb-table :column="tableColumn" :tableData="tableData" :spanMethod="spanMethod" :indexWidth="60"
            :border="true" :bottomElement="['pb-page']" :indexshow="false" :cellPadding="4" :showSummary="true"
            :getSummaries="getSummaries">
            <template #onlineStatus="{ row }">
              <div class="flex items-center">
                <p class="dot mr-1" :style="{
                  background:
                    row.onlineStatus == 'offline' ? '#F52F3EFF' : row.onlineStatus == 'online' ? '#09B562FF' : '#acacac',
                }"></p>
                {{ row.onlineStatus == 'offline' ? "离线" : row.onlineStatus == 'online' ? "在线" : "未知" }}
              </div>
            </template>
            <template #remark="{ row }">
              <div>
                <el-popover placement="top" :width="200" trigger="hover" :content="row.remark">
                  <template #reference>
                    <div class="remark">{{ row.remark }}</div>
                  </template>
                </el-popover>
              </div>
            </template>
          </pb-table>
          <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
            @onChange="getTableList" :total="pages.total"></pb-pagination>
        </div>
      </pb-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from "dayjs"
import { getStatisticsListApi, getIncomeSourceListApi, DownStatisticsxcelApi, incomeImportExcel, DownteplateStatisApi } from '@/api/incomeStatistics'
import { GetkitchenListApi } from '@/api/Purchasing';
import { formattedDate } from "@/utils/moment"
const importDateChange = (time) => {
  // console.log(time, '222')
  importDate.value = formattedDate(time, 'YYYY-MM-DD')
  // console.log(importDate.value, '222')
}
const downtemplateExcelFn = () => {
  DownteplateStatisApi({
  }).then(response => {
    const disposition = response.headers['content-disposition'];
    // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
    const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
    const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
    let decodedFilename = ''
    if (encodedFilenamePart) {
      // 解码文件名
      decodedFilename = decodeURIComponent(encodedFilenamePart);
      decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
      // 输出解码后的文件名
      console.log("Decoded filename:", decodedFilename);
    } else {
      decodedFilename = "食堂端消费统计" + new Date().getTime() + '.xlsx'
      // 如果没有找到包含文件名的部分，输出警告信息
      // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
    }
    let blob = new Blob([response.data]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    // console.log(href, '22href')
    downloadElement.href = href;
    downloadElement.download = decodedFilename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}
const downStatisticFN = () => {
  DownStatisticsxcelApi({
    ...incomeForm.value
  }).then(response => {
    const disposition = response.headers['content-disposition'];
    // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
    const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
    const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
    let decodedFilename = ''
    if (encodedFilenamePart) {
      // 解码文件名
      decodedFilename = decodeURIComponent(encodedFilenamePart);
      decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
      // 输出解码后的文件名
      console.log("Decoded filename:", decodedFilename);
    } else {
      decodedFilename = "食堂消费统计" + new Date().getTime() + '.xlsx'
      // 如果没有找到包含文件名的部分，输出警告信息
      // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
    }
    let blob = new Blob([response.data]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    // console.log(href, '22href')
    downloadElement.href = href;
    downloadElement.download = decodedFilename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}
const conmeSourelist = ref([] as any)
const kitchenList = ref([] as any)
const importDate = ref(dayjs(new Date()).format('YYYY-MM-DD'))
const formOrigin = () => ({
  incomeSource: '',
  tenantId: "",
  statisticsStartDate: dayjs().startOf('week').format('YYYY-MM-DD'),
  statisticsStopDate: dayjs().endOf('week').format('YYYY-MM-DD'),
});
const incomeForm = ref(formOrigin());
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const pages = ref(pageInit());

// 设置时间
const planDateRang = ref([incomeForm.value.statisticsStartDate, incomeForm.value.statisticsStopDate])
const dateChange = () => {
  incomeForm.value.statisticsStartDate = dayjs(planDateRang.value[0]).format('YYYY-MM-DD')
  incomeForm.value.statisticsStopDate = dayjs(planDateRang.value[1]).format('YYYY-MM-DD')
}

const searchFn = () => {
  getTableList()
}
const resetFn = () => {
  incomeForm.value = formOrigin()
  pages.value = pageInit()
  getTableList()
}


const tableColumn = reactive([
  {
    key: 'index',
    name: '序号',
    width: 50,
  },
  {
    key: "tenantName",
    name: "单位名称",
  },
  {
    key: "statisticsDate",
    name: "登记日期",
    width: 70
  },
  {
    key: "totalAmount",
    name: "总金额（元）",
    align: 'right',
  },
  {
    key: "incomeSourceName",
    name: "收入来源",
  },
  {
    key: "incomeCategoryName",
    name: "收入类型",
  },
  {
    key: "incomeAmount",
    name: "收入金额(元)",
    align: 'right',
  },
  {
    key: "dinersCount",
    name: "就餐人次",
    align: 'right',
  },
  {
    key: "deliveryFee",
    name: "配送费",
    align: 'right',
  },
  {
    key: "creator",
    name: "创建人",
  },
  {
    key: "createTime",
    name: "创建时间",
  },
  // {
  //   slot: "opration",
  //   name: "操作",
  //   fixed: 'right'
  // },

])


// 计算指定列的合并信息
const computeCell = (tableList, mergeKeys) => {
  const cellList = [];
  let count = 0;
  let prevKey = null;
  for (let i = 0; i < tableList.length; i++) {
    // 生成合并键（序号 + 需要合并的列）
    const currentKey = mergeKeys.map(key => tableList[i][key]).join('|');
    if (i === 0) {
      cellList.push(1);
      count = 0;
      prevKey = currentKey;
    } else {
      if (currentKey === prevKey) {
        cellList[count]++;
        cellList.push(0);
      } else {
        cellList.push(1);
        count = i;
        prevKey = currentKey;
      }
    }
  }
  return cellList;
};

// 合并方法
const spanMethod = ({ rowIndex, columnIndex }) => {
  const columns = tableColumn.map(col => col.key);
  const column = columns[columnIndex];

  // 定义各列的合并规则
  const mergeRules = {
    index: ['index'],
    tenantName: ['index', 'tenantName'],
    statisticsDate: ['index', 'tenantName'],
    totalAmount: ['index', 'tenantName'],
    incomeSourceName: ['index', 'incomeSourceName']
  };

  if (mergeRules[column]) {
    const cellList = computeCell(tableData.value, mergeRules[column]);
    const fRow = cellList[rowIndex];
    return {
      rowspan: fRow,
      colspan: fRow > 0 ? 1 : 0
    };
  }

  return { rowspan: 1, colspan: 1 };
};

const getSummaries = ({ columns, data }: any) => {
  const sums = [] as any;
  columns.forEach((column: any, index: any) => {
    if (index === 0) {
      sums[index] = '汇总';
      return;
    }
    // 总金额有合并行单独计算汇总数据
    if (column.property == 'totalAmount') {
      const seen = new Map()
      const totalAmount = data.filter(item => {
        const alSeen = seen.get(item.index)
        if (alSeen) return false
        seen.set(item.index, true)
        return true
      })
      const values = totalAmount.map(item => Number(item['totalAmount']) || 0);
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return parseFloat((prev + curr).toFixed(2));
        } else {
          return prev;
        }
      }, 0);
    }
    const values = data.map(item => Number(item[column.property]) || 0);
    let countList = ['incomeAmount', 'dinersCount', 'deliveryFee']
    if (countList.includes(column.property)) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return parseFloat((prev + curr).toFixed(2));
        } else {
          return prev;
        }
      }, 0);
    }
  });
  return sums;
}
const tableData = ref([] as any)
const getTableList = () => {
  getStatisticsListApi({
    "currentPage": pages.value.currentPage,
    "pageSize": pages.value.pageSize,
    ...incomeForm.value
  }).then(res => {
    tableData.value = []; // 清空之前的数据
    let Bomdata = res.data.records
    pages.value.total = res.data.total
    if (Bomdata.length > 0) {
      Bomdata.forEach((ele, index) => {
        if (ele.incomeStatisticsSourceVOList && ele.incomeStatisticsSourceVOList.length > 0) {
          ele.incomeStatisticsSourceVOList.forEach((secondLevelEle) => {
            if (secondLevelEle.incomeStatisticsCategoryVOList && secondLevelEle.incomeStatisticsCategoryVOList.length > 0) {
              secondLevelEle.incomeStatisticsCategoryVOList.forEach((thirdLevelEle) => {
                thirdLevelEle.index = index + 1;
                tableData.value.push({
                  ...ele,
                  ...secondLevelEle,
                  ...thirdLevelEle
                });
              });
            } else {
              secondLevelEle.index = index + 1;
              tableData.value.push({
                ...ele,
                ...secondLevelEle
              });
            }
          });
        } else {
          ele.index = index + 1;
          tableData.value.push(ele);
        }
      });
    }
  })
}
onMounted(() => {
  getTableList()
  getIncomeSourceListApi({}).then(res => {
    conmeSourelist.value = res.data.map(el => {
      return {
        value: el.incomeSourceCode,
        lable: el.incomeSourceName
      }
    })
  })
  GetkitchenListApi().then(res => {
    kitchenList.value = res.data
  })
})
</script>
<style lang="scss" scoped>
.divide-css {
  width: 100%;
  height: 16px;
  background: #F3F3F3;
}
</style>